package com.demo.security.custom.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import com.demo.security.custom.ex.InvalidVerifyCodeException;
import com.demo.security.custom.handler.MyAuthenticationFailureHandler;

/**
 * 验证码校验
 * 
 * @author OL
 *
 */
@Component
public class CaptchaVerifyFilter extends OncePerRequestFilter {

    private static final Logger log = LoggerFactory.getLogger(CaptchaVerifyFilter.class);

    @Autowired
    private MyAuthenticationFailureHandler loginFailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if (request.getRequestURI().equals("/login") && request.getMethod().equalsIgnoreCase("POST")) {
            try {
                this.validate(request);
                // 校验通过则放行
            } catch (InvalidVerifyCodeException e) {
                loginFailureHandler.onAuthenticationFailure(request, response, e);
                return;
            }
        }
        filterChain.doFilter(request, response);
    }

    /**
     * 验证保存在session的验证码和表单提交的验证码是否一致
     */
    private void validate(HttpServletRequest request) {
        String verifyCode = request.getParameter("verifyCode");
        if (verifyCode == null || verifyCode.trim().length() == 0) {
            // 验证码校验逻辑 TODO
            log.info("验证码错误: {}", verifyCode);
            throw new InvalidVerifyCodeException("验证码错误");
        }
    }
}